// app.js
var flag = false

App({
  onLaunch: async function () {
    if (flag) {
      return
    }

    flag = true

    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      await wx.cloud.init({
        // env 参数说明：
        //   env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境（第一个创建的环境）
        env: 'zjn-0gzb74lr2a7692b1',
        traceUser: true,
      });
    }

    await this.getUserInfo()
    await this.delay(1000)

    if (this.globalData.docId.length === 0) {
      await this.initUserInfo()
    }
  },

  onShow() {
    return
  },

  delay(milSec) {
    return new Promise(resolve => {
      setTimeout(resolve, milSec)
    })
  },

  async initUserInfo() {
    const db = wx.cloud.database()
    await db.collection('user_info').add({
      data: {
        userName: '微信用户',
        userPhone: '',
        imgUrl: 'cloud://zjn-0gzb74lr2a7692b1.7a6a-zjn-0gzb74lr2a7692b1-1317297115/image/me_open.jpg'
      }
    })

    await this.getUserInfo()
  },

  async getUserInfo() {
    var that = this
    await wx.cloud.callFunction({
      name:'login_get_openid',
      
    }).then(res => {
        that.globalData.openid = res.result.openid
        // 从数据库中查找是否有这条记录
        wx.cloud.database().collection('user_info').where({
          _openid: res.result.openid
        }).get().then(result => {
          if (result.data.length > 0) {
            var query_res = result.data[0]
            that.globalData.userName = query_res.userName
            that.globalData.userPhone = query_res.userPhone
            that.globalData.imgUrl = query_res.imgUrl
            that.globalData.docId = query_res._id
          }
        })
    })
  },

  setUserInfo(userName, userPhone, imgUrl) {
    this.globalData.userName = userName
    this.globalData.userPhone = userPhone
    this.globalData.imgUrl = imgUrl
  },


  checkTime(date) {
    var d = new Date(date)
    var now = new Date()
    if (d.getTime() > now) {
      return true
    }

    return false
  },
 async getCinemaId(movieId){
  await wx.cloud.collection('session_info').where({
    movieId: movieId
  }).get().then(res => {
    const sessions = res.data;
    const cinemaIds = sessions.map(session_info => session_info.cinemaId);
    return cinemaIds
  }).catch(err => {
    console.error(err);
  });
 },
  async getTimeRightSession(movieId) {
    var ret = []
    var that = this
    await wx.cloud.database().collection('session_info').where({
      movieId: movieId
    }).get().then(res => {
      for (let i in res.data) {
        if (that.checkTime(res.data[i].date + ' ' + res.data[i].startTime)) {
          ret.push(JSON.parse(JSON.stringify(res.data[i])))
        }
      }
    })

    return ret
  },
  async getTimeRightSession1(movieId,cinemaId) {
    var ret = []
    var that = this
    await wx.cloud.database().collection('session_info').where({
      movieId: movieId,
      cinemaId:cinemaId
    }).get().then(res => {
      for (let i in res.data) {
        if (that.checkTime(res.data[i].date + ' ' + res.data[i].startTime)) {
          ret.push(JSON.parse(JSON.stringify(res.data[i])))
        }
      }
    })
    return ret
  },

  async getAppointTimeSession(movieId, cinemaId, date) {
    var ret = []
    var that = this
    await wx.cloud.database().collection('session_info').where({
      movieId: movieId,
      cinemaId: cinemaId,
      date: date  
    }).orderBy('startTime','asc').get().then(res => {
      for (let i in res.data) {
        if (that.checkTime(res.data[i].date + ' ' + res.data[i].startTime)) {
          ret.push(JSON.parse(JSON.stringify(res.data[i])))
        }
      }
    })

    return ret
  },

  globalData:{
    userName:'',
    userPhone: '',
    imgUrl: 'cloud://zjn-0gzb74lr2a7692b1.7a6a-zjn-0gzb74lr2a7692b1-1317297115/image/me_open.jpg',
    openid: '',
    docId: ''
  }
});
